<?php
/**
 * 常用函数
 * 
 * ============================================================================
 * 版权所有 (c) 2001-2009，南宁市孟捷网络科技有限责公司，并保留所有权利。
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 *
 * @author      cmpan
 * @copyright   Copyright (c) 2009-2010 MJieNET Inc. (http://www.mjie.net)
 * @license     http://www.mjie.net/license/1_0.txt
 */

/**
 * 变量的quote for mysql
 *
 * @param array|string $var
 * @return array|string
 */
function quotesHttpVars($var) {
	if(empty($var)) return $var;

	if (is_array($var)) {
		return array_map('quotesHttpVars', $var);
	} else {
		if (get_magic_quotes_gpc()) {
			// 当前需要以 \ 为转义符
			// 如果 magic_quotes_sybase = On, 我们先把 '' 替换成 ', 然后在 addslashes
			// 否则系统自动quotes
			if (ini_get('magic_quotes_sybase')) {
				$var = str_replace("''", "'", $var);
				$var = addslashes($var);
			} //else { $var = $var;}
		} else{
			$var = addslashes($var);
		}
		
		return trim($var);
	}
}

/**
 * 多维数组的转义 for mysql
 *
 * @param array|string $var
 * @return array|string
 */
function quotesVars($var) {
	if(empty($var)) return $var;
	return is_array($var) ? array_map('quotesVars', $var) : addslashes($var);
}

/**
 * 去掉转义
 *
 * @param string|array $var
 * @return string|array
 */
function unquoteVars($var) {
    if(empty($var)) return '';

	if (is_array($var)) {
		return array_map('unquoteVars', $var);
	}
	
	if (is_string($var)) {
		return stripslashes($var);
	}
	
	return $var;
}

/**
 * 默认异常处理
 *
 * @param object $e 异常对象
 */
function exceptionHandler($e) {
	print "\n<pre style=\"border: 1px solid #FF0000; padding:12px;\">\n";
	print($e);
	print "\n</pre>\n";
	exit;
}

/**
 * 错误处理
 *
 * @param 错误码 $no
 * @param 错误信息 $msg
 * @param 发生错误的文件 $file
 * @param 错误行号 $line
 * @param 错误上下文 $ctx
 */
function errorHandler($no, $msg, $file, $line, $ctx) {
	if((UE_Config::get('debug') && $no) || ($no & (E_ALL ^ E_NOTICE ^ E_WARNING))) {
	//if($no) {
		$types = array(
			1    => 'error',
			2    => 'warning',
			4    => 'parse error',
			8    => 'notice',
			16   => 'core error',
			32   => 'core warning',
			64   => 'compile error',
			128  => 'compile warning',
			256  => 'user error',
			512  => 'user warning',
			1024 => 'user notice',
			2048 => 'strict warning',
			4096 => 'recoverable fatal error'
		);
		
		if (UE_Config::get('debug')) {
			$errLog = '';
			$errLog .= "{$types[$no]}: {$msg}\n";
			$errLog .= "line: {$line} \n";
			$errLog .= "file: {$file}\n\n";
			
			file_put_contents(DATA_DIR . '/logs/errorHandler.log', $errLog, FILE_APPEND);
		}
		
		print "<pre style=\"border:1px solid #FF0000; padding:16px;\">\n";
		print "Error occured:\n";
		print 'type : ' . $types[$no] . "\n";
		print 'msg  : <b style="color: #FF0000;">' . $msg . "</b>\n";
		print 'file : ' . $file . "\n";
		print 'line : ' . $line . "\n";
		print 'ctx  : ';
		print_r($ctx);
		print "</pre>";
		
		
    	//exit;
	}
}

/**
 * 当前php进程使用了的内存（M）, 四舍五入到小数点后4位
 */
function memUsed() {
	if (function_exists('memory_get_usage')) {
		return round(memory_get_usage()/(1024*1024), 4); // by M
	} else {
		return 0;
	}
}

/**
 * 把字符串左边给定的字符去掉
 */
function ltrimStr($string, $needle, $trimAll = false) {
	// 如果字符串左边字符和左边要去掉的字符一致则去掉
	if($needle === substr($string, 0, strlen($needle))){
		$string = substr($string, strlen($needle));
		$trimAll && $string = ltrimStr($string, $needle, true);
	}

	return $string;
}

/**
 * 把字符串右边给定的字符去掉
 */
function rtrimStr($string, $needle, $trimAll = false) {
	// 如果字符串右边字符和要去掉的字符一致则去掉
	if($needle === substr($string,  - strlen($needle))){
		$string = substr($string, 0,  - strlen($needle));
		$trimAll && $string = rtrimStr($string, $needle, true);
	}

	return $string;
}

/**
 * 把字符串两头给定的字符去掉
 */
function trimStr($string, $needle, $trimAll = true) {
	$string = rtrimStr($string, $needle, $trimAll);
	$string = ltrimStr($string, $needle, $trimAll);

	return $string;
}

/**
 * 把数据写入data目录下的文件中
 *
 * @param string $file
 * @param string $varName
 * @param mixed  $data
 */
function writeData($file, $data) {
	$file = secureFile($file);
	
	(!is_file(dirname($file))) && mkdirs(dirname($file));
	
	if(@file_put_contents($file, '<?php return '.var_export($data, true).';', LOCK_EX)) {
		return true;
	} else {
		return false;
	}
}

/**
 * 安全目录
 *
 * @param string $dir
 * @return string
 */
function secureDir($dir) {
    $dir = rtrim($dir, '/\\');
	$dir = str_replace(array('\\', '../', './'), array('/', '', ''), $dir);
	
	if (substr($dir, 0, strlen(SITE_DIR)) != SITE_DIR) {
		$dir = SITE_DIR.'/'.ltrim($dir, '/');
	}
	
	return $dir;
}

/**
 * 安全文件
 *
 * @param string $dir
 * @return string
 */
function secureFile($file) {
	return secureDir(dirname($file)) . '/' . basename($file);
}

/**
 * 获取客户端使用的协议
 *
 * @return string protocol
 */
function clientProtocol() {
    static $protocol;
	if($protocol) return $protocol;
	
	$protocol = @$_SERVER["SERVER_PROTOCOL"];
	if ('HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol) {
		$protocol = 'HTTP/1.0';
	}
	
	return $protocol;
}

/**
 * 客户端是否是搜索引擎的爬虫 
 *
 * @return bool
 */
function isRobot() {
	static $isRobot = null;
	if(null !== $isRobot) {
		return $isRobot;
	}
	
	$spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
	$browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';

	if(preg_match("/($browsers)/i", $_SERVER['HTTP_USER_AGENT'])) {
		$isRobot = false;
	} elseif(preg_match("/($spiders)/i", $_SERVER['HTTP_USER_AGENT'])) {
		$isRobot = true;
	} else {
		$isRobot = false;
	}

	return $isRobot;
}

/**
 * 获取服务器真实ip
 *
 * @return string
 */
function realServerIP() {
    static $serverIP = null;

    if ($serverIP !== null) {
        return $serverIP;
    }

    if (isset($_SERVER)) {
        if (isset($_SERVER['SERVER_ADDR'])) {
            $serverIP = $_SERVER['SERVER_ADDR'];
        } else {
            $serverIP = '0.0.0.0';
        }
    } else {
        $serverIP = getenv('SERVER_ADDR');
    }

    return $serverIP;
}

if(!function_exists('lcfirst')) {
    /**
     * 字符串首字母小写
     *
     * @param string $str
     * @return string the resulting string.
     */
    function lcfirst($str) {
        $str[0] = strtolower($str[0]);
        return (string)$str;
    }
}


/**
 * 获得浏览器名称和版本
 *
 * @return string
 */
function userBrowser() {
	if (empty($_SERVER['HTTP_USER_AGENT'])) {
		return '';
	}

	$agent    = $_SERVER['HTTP_USER_AGENT'];
	$browser  = '';
	$version  = '';

	if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) {
		$browser = 'Internet Explorer';
		$version = $regs[1];
	} elseif (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) {
		$browser = 'FireFox';
		$version = $regs[1];
	} elseif (preg_match('/Maxthon/i', $agent, $regs)) {
		$browser = '(Internet Explorer ' .$version. ') Maxthon';
		$version = '';
	} elseif (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) {
		$browser = 'Opera';
		$version = $regs[1];
	} elseif (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
		$browser = 'OmniWeb';
		$version = $regs[2];
	} elseif (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) {
		$browser = 'Netscape';
		$version = $regs[2];
	} elseif (preg_match('/safari\/([^\s]+)/i', $agent, $regs)) {
		$browser = 'Safari';
		$version = $regs[1];
	} elseif (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) {
		$browser = '(Internet Explorer ' .$version. ') NetCaptor';
		$version = $regs[1];
	} elseif (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) {
		$browser = 'Lynx';
		$version = $regs[1];
	}

	if (!empty($browser)) {
	   return addslashes($browser . ' ' . $version);
	} else {
		return 'Unknow Browser';
	}
}


/**
 * 获得客户端的操作系统
 *
 * @return string
 */
function userOS() {
	if (empty($_SERVER['HTTP_USER_AGENT'])) {
		return 'Unknown';
	}

	$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	$os    = '';

	if (strpos($agent, 'win') !== false) {
		if (strpos($agent, 'nt 5.1') !== false) {
			$os = 'Windows XP';
		} elseif (strpos($agent, 'nt 5.2') !== false) {
			$os = 'Windows 2003';
		} elseif (strpos($agent, 'nt 5.0') !== false) {
			$os = 'Windows 2000';
		} elseif (strpos($agent, 'nt 6.0') !== false) {
			$os = 'Windows Vista';
		} elseif (strpos($agent, 'nt') !== false) {
			$os = 'Windows NT';
		} elseif (strpos($agent, 'win 9x') !== false && strpos($agent, '4.90') !== false) {
			$os = 'Windows ME';
		} elseif (strpos($agent, '98') !== false) {
			$os = 'Windows 98';
		} elseif (strpos($agent, '95') !== false) {
			$os = 'Windows 95';
		} elseif (strpos($agent, '32') !== false) {
			$os = 'Windows 32';
		} elseif (strpos($agent, 'ce') !== false) {
			$os = 'Windows CE';
		}
	} elseif (strpos($agent, 'linux') !== false) {
		$os = 'Linux';
	} elseif (strpos($agent, 'unix') !== false) {
		$os = 'Unix';
	} elseif (strpos($agent, 'sun') !== false && strpos($agent, 'os') !== false) {
		$os = 'SunOS';
	} elseif (strpos($agent, 'ibm') !== false && strpos($agent, 'os') !== false) {
		$os = 'IBM OS/2';
	} elseif (strpos($agent, 'mac') !== false && strpos($agent, 'pc') !== false) {
		$os = 'Macintosh';
	} elseif (strpos($agent, 'powerpc') !== false) {
		$os = 'PowerPC';
	} elseif (strpos($agent, 'aix') !== false) {
		$os = 'AIX';
	} elseif (strpos($agent, 'hpux') !== false) {
		$os = 'HPUX';
	} elseif (strpos($agent, 'netbsd') !== false) {
		$os = 'NetBSD';
	} elseif (strpos($agent, 'bsd') !== false) {
		$os = 'BSD';
	} elseif (strpos($agent, 'osf1') !== false) {
		$os = 'OSF1';
	} elseif (strpos($agent, 'irix') !== false) {
		$os = 'IRIX';
	} elseif (strpos($agent, 'freebsd') !== false) {
		$os = 'FreeBSD';
	} elseif (strpos($agent, 'teleport') !== false) {
		$os = 'teleport';
	} elseif (strpos($agent, 'flashget') !== false) {
		$os = 'flashget';
	} elseif (strpos($agent, 'webzip') !== false) {
		$os = 'webzip';
	} elseif (strpos($agent, 'offline') !== false) {
		$os = 'offline';
	} else {
		$os = 'Unknown';
	}

	return $os;
}

/**
 * 获得用户操作系统的换行符
 *
 */
function userCrlf() {
	static $crlf = null;
	if ($crlf !== null) {
		return $crlf;
	}
	
	if(empty($_SERVER['HTTP_USER_AGENT'])) {
		return $crlf = "\n";
	}
	
	if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win')) {
	    $crlf = "\r\n";
	} elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac')) {
	    $crlf = "\r"; // for old MAC OS
	} else {
	    $crlf = "\n";
	}
	
	return $crlf;
}

/**
 * 删除文件夹（包括有子目录或有文件）
 *
 * @param string $dir 目录
 */
function realRemoveDir($dir) {
	$dir = rtrim($dir, '/\\');
	$dir = str_replace(array('\\', '../', './'), array('/', '', ''), $dir);
	
	// 不删除非法路径
	if (substr($dir, 0, strlen(SITE_DIR)) != SITE_DIR) {
		return false;
	}
	
    if(!$d = @dir($dir)) return;
    while (false !== ($entry = @$d->read())) {
        if($entry == '.' || $entry == '..') continue;
        if (is_dir($dir.'/'.$entry)) {
            realRemoveDir($dir.'/'.$entry);
        } else {
           @unlink($dir.'/'.$entry);
        }
    }
    
    @$d->close();
    @rmdir($dir);
}

/**
 * 删除目录下 的所有文件
 *
 * @param string $dir
 */
function clearDir($dir) {
	$dir = rtrim($dir, '/\\');
		
    if(!$d = @dir($dir)) return;
    while (false !== ($entry = @$d->read())) {
        if($entry == '.' || $entry == '..') continue;
        if (is_dir($dir.'/'.$entry)) {
            realRemoveDir($dir.'/'.$entry);
        } else {
           @unlink($dir.'/'.$entry);
        }
    }    
    @$d->close();
}


/**
 * 把全角字符全部换成半角字符再返回
 *
 * @param string $str
 * @return string
 */
function toSemiangle($str) {
	$arr = array(
	"０" => "0", "１" => "1", "２" => "2", "３" => "3", "４" => "4", "５" => "5",
	"６" => "6", "７" => "7", "８" => "8", "９" => "9", "Ａ" => "A", "Ｂ" => "B",
	"Ｃ" => "C", "Ｄ" => "D", "Ｅ" => "E", "Ｆ" => "F", "Ｇ" => "G", "Ｈ" => "H",
	"Ｉ" => "I", "Ｊ" => "J", "Ｋ" => "K", "Ｌ" => "L", "Ｍ" => "M", "Ｎ" => "N",
	"Ｏ" => "O", "Ｐ" => "P", "Ｑ" => "Q", "Ｒ" => "R", "Ｓ" => "S", "Ｔ" => "T",
	"Ｕ" => "U", "Ｖ" => "V", "Ｗ" => "W", "Ｘ" => "X", "Ｙ" => "Y", "Ｚ" => "Z",
	"ａ" => "a", "ｂ" => "b", "ｃ" => "c", "ｄ" => "d", "ｅ" => "e", "ｆ" => "f",
	"ｇ" => "g", "ｈ" => "h", "ｉ" => "i", "ｊ" => "j", "ｋ" => "k", "ｌ" => "l",
	"ｍ" => "m", "ｎ" => "n", "ｏ" => "o", "ｐ" => "p", "ｑ" => "q", "ｒ" => "r",
	"ｓ" => "s", "ｔ" => "t", "ｕ" => "u", "ｖ" => "v", "ｗ" => "w", "ｘ" => "x",
	"ｙ" => "y", "ｚ" => "z", "（" => "(", "）" => ")", "［" => "[", "］" => "]",
	"【" => "[", "】" => "]", "〖" => "[", "〗" => "]", "「" => "[", "」" => "]",
	"『" => "[", "』" => "]", "｛" => "{", "｝" => "}", "《" => "<", "》" => ">",
	"％" => "%", "＋" => "+", "—" => "-", "－" => "-", "～" => "-", "：" => ":",
	"。" => ".", "、" => ",", "，" => ".", "、" => ".", "；" => ",", "？" => "?",
	"！" => "!", "…" => "-", "‖" => "|", "　" => " ", "＇" => "`", "｀" => "`",
	"｜" => "|", "〃" => "\"", "＂" => "\"");
	return strtr($str, $arr);
}


/**
 * 十六进制字符串转换成二进制字符串
 *
 * @param string $hexData
 * @return string
 */
function hex2bin($hexData) {
	$binData = '';
	for($i=0; $i < strlen($hexData); $i += 2) {
		$binData .= chr(hexdec(substr($hexData, $i, 2)));
	}
	return $binData;
}

/**
 * 切割字符串
 *
 * @param string $string 将切割的字符窜
 * @param int $length 返回多长的字符窜
 * @param bool $append 切割后是否在后面添加字符串(...)
 * @param string $appendStr 切割后在后面添加的字符串
 * @return string
 */
function realSubstr($string, $length = 0, $append = false, $appendStr = '...') {
	if (strlen($string) <= $length) {
		return $string;
	}

	$string = str_replace(array("&amp;", "&quot;", "&lt;", "&gt;"), array("&", "\"", "<", ">"), $string);
	$strCut = "";

	$n = $tn = $noc = 0;

	while($n < strlen($string)) {
		$t = ord($string[$n]);
		if($t == 9 || $t == 10 || 32 <= $t && $t <= 126) {
			$tn = 1;
			$n++;
			$noc++;
		} else if (194 <= $t && $t <= 223) {
			$tn = 2;
			$n += 2;
			$noc += 2;
		} else if (224 <= $t && $t < 239) {
			$tn = 3;
			$n += 3;
			$noc += 2;
		} else if (240 <= $t && $t <= 247) {
			$tn = 4;
			$n += 4;
			$noc += 2;
		} else if (248 <= $t && $t <= 251) {
			$tn = 5;
			$n += 5;
			$noc += 2;
		} else if ($t == 252 || $t == 253) {
			$tn = 6;
			$n += 6;
			$noc += 2;
		} else {
			$n++;
		}
		if ($length <= $noc) {
			break;
		}
	}

	if ($length < $noc) {
		$n -= $tn;
	}

	$strCut = substr($string, 0, $n);

	$strCut = str_replace(array("&", "\"", "<", ">"), array("&amp;", "&quot;", "&lt;", "&gt;"), $strCut);
	if ($append && $string != $strCut) {
		$strCut .= $appendStr;
	}

	return $strCut;
}


/**
 * 输出js内容
 *
 * @param string $js js程序代码
 * @return string
 */
function js($js) {
	return "<script type='text/javascript'>\n{$js}</script>\n";
}

/**
 * 获取唯一id
 * 解决uniqid()在多核/多CPU环境下产生重复值的问题
 *
 * @return string
 */
function realUniqid() {
	isset($_SERVER['REMOTE_ADDR']) || $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
	return uniqid(sprintf('%x', crc32(uniqid($_SERVER['REMOTE_ADDR'], true))));
}


function writeJs($html) {
	$js = str_replace(array("\r\n", "\n", '"', "<script "), array(' ', ' ', '\"', '<scr"+"ipt '), $html);
	return "document.write(\"{$js}\");\n";
}

if (!function_exists('hash_hmac')) {
	/**
	 * hash_hmac PHP实现
	 *
	 * @param string $algo 使用的哈希计算函数
	 * @param string $data 要哈希的数据
	 * @param string $key  密钥
	 * @param bool $raw_output 是否返回原始二进制数据，为否则返回十六进制小写数据
	 * @return string
	 */
	function hash_hmac($algo, $data, $key, $raw_output = false) {
	    $algo = strtolower($algo);
	    $pack = 'H'.strlen($algo('test'));
	    $opad = str_repeat(chr(0x5C), 64);
	    $ipad = str_repeat(chr(0x36), 64);
	
	    if (strlen($key) > 64) {
	        $key = str_pad(pack($pack, $algo($key)), 64, chr(0x00));
	    } else {
	        $key = str_pad($key, 64, chr(0x00));
	    }
	
	    for ($i = 0; $i < strlen($key) - 1; $i++) {
	        $opad[$i] = $opad[$i] ^ $key[$i];
	        $ipad[$i] = $ipad[$i] ^ $key[$i];
	    }
	
	    $output = $algo($opad.pack($pack, $algo($ipad.$data)));
	
	    return ($raw_output) ? pack($pack, $output) : $output;
	}
}

/**
 * 替换html标签
 *
 * @param string $string
 * @param string|array $tag
 * @param string|array $replace
 * @param string $feed
 * @return string
 */
function htmlTagReplace($string, $tag = 'p', $replace = 'div', $feed = '') {
	$tag = (array)$tag;
	$replace = (array)$replace;
	foreach ($tag as $key => $_tag) {
		$string = preg_replace("/<$_tag(.*?)>(.*?)<\/$_tag>/s", "<{$replace[$key]}\\1>\\2</{$replace[$key]}>", $string);
		$string = preg_replace("/<$_tag(.*?)\/>/s", "<{$replace[$key]}\\1/>", $string);
	}
	
	return $string ;

}

/**
 * 通过分类获取条目
 *
 * @param int $termId  分类id
 * @param int $row   返回行数
 */
function getItemsByTermId($termId, $row = 10, $getSons = false, $len = 0, $requireIcon = false, $pidOrder = 'DESC') {
	global $db, $CATS;
	$db = UE_DB::factory();
	$cats = UE_Cache::createCache()->get('categories');
		
	$termIds[] = $termId;
	if($getSons) {
		foreach($cats as $cat) {
			if($cat['cat_parent'] == $termId) {
				$termIds[] = $cat['cat_id'];
			}
		}
	}

	$where = '';
	if ($_GET['app'] == UE_Config::get('default_app') && $_GET['ctl'] == UE_Config::get('default_ctl') && $_GET['act'] == UE_Config::get('default_act')) {
		//$where .= ' AND p.post_show_in_home = 1 ';
	}
	
	if($requireIcon) {
		$where .= " AND p.post_icon != '' ";
	}
	
	$sql = "SELECT *
	        FROM mj_posts p
			LEFT JOIN mj_cat c ON c.cat_id = p.cat_id
			WHERE c.cat_id IN ('".join("', '", $termIds)."')
		      AND p.post_status = 'publish'
			  $where
			ORDER BY post_order_dateline DESC, p.post_order, p.post_id $pidOrder
			LIMIT $row";
	$rows = $db->getAll($sql, 1);
	
	if(!$rows) { return array();}
	
	foreach ($rows as $key => $row) {
		if($len) {
			$rows[$key]['post_title'] = realSubstr($rows[$key]['post_title'], $len, false);
		}
		
		if($row['post_icon']) {
			$rows[$key]['post_icon'] = UE::context() . $row['post_icon'];
			$rows[$key]['post_icon_encoded'] = UE_Encoder::encode(UE::context() . $row['post_icon']);
		}
		
	}
	//print_r($rows);
	return $rows;
}

/**
 * 当前页面是否是首页
 */
function isHome() {
	if(UE_Config::get('default_app') == $_GET['app'] 
	&& UE_Config::get('default_ctl') == $_GET['ctl'] 
	&& UE_Config::get('default_act') == $_GET['act']) {
		return true;
	}
	return false;
}

if(!function_exists('mb_strlen')) {
    function mb_strlen($str) {
		return preg_match_all("/.{1}/us", $str, $dummy);
	}	
}


//
/**
 * UTF-8 转GB编码
 *
 * @param string $gbstr UTF-8字符串
 * @return string gbk字符串
 */
function utf82gbk($utfstr) {
	if(function_exists('iconv')) {
		return iconv('utf-8','gbk//ignore',$utfstr);
	} elseif(function_exists('mb_convert_encoding')) {
		return mb_convert_encoding($utfstr, 'GBK', 'UTF-8');
	}
	
	if(trim($utfstr)=="") {
		return $utfstr;
	}
	
	static $UC2GBTABLE;
	if(empty($UC2GBTABLE)) {
		$filename = dirname(__FILE__)."/_data/gbk-utf8.dat";
		$fp = fopen($filename, "r");
		while($l = fgets($fp, 15)) {
			$UC2GBTABLE[hexdec(substr($l, 7, 6))] = hexdec(substr($l, 0, 6));
		}
		
		fclose($fp);
	}
	$gbkstr = "";
	$ulen = strlen($utfstr);
	for($i=0;$i<$ulen;$i++) {
		$c = $utfstr[$i];
		$cb = decbin(ord($utfstr[$i]));
		if(strlen($cb)==8) {
			$csize = strpos(decbin(ord($cb)),"0");
			for($j=0;$j < $csize;$j++) {
				$i++; $c .= $utfstr[$i];
			}
			$c = utf82u($c);
			if(isset($UC2GBTABLE[$c])) {
				$c = dechex($UC2GBTABLE[$c]+0x8080);
				$gbkstr .= chr(hexdec($c[0].$c[1])).chr(hexdec($c[2].$c[3]));
			} else {
				$gbkstr .= "&#".$c.";";
			}
		}
		else {
			$gbkstr .= $c;
		}
	}
	$gbkstr = trim($gbkstr);
	return $gbkstr;
}

/**
 * GB转UTF-8编码
 *
 * @param string $gbstr gbk字符串
 * @return string utf-8字符串
 */
function gbk2utf8($gbstr) {
	if(function_exists('iconv')) {
		return iconv('gbk','utf-8//ignore',$gbstr);
	} elseif (function_exists('mb_convert_encoding')) {
		return mb_convert_encoding($gbstr, 'UTF-8', 'GBK');
	}
	
	if(trim($gbstr)=="") {
		return $gbstr;
	}
	
	static $GBK2UTF8_CODETABLE;
	
	if(empty($GBK2UTF8_CODETABLE)) {
		$filename = dirname(__FILE__)."/_data/gbk-utf8.dat";
		$fp = fopen($filename, "r");
		while ($l = fgets($fp,15)) {
			$GBK2UTF8_CODETABLE[hexdec(substr($l, 0, 6))] = substr($l, 7, 6);
		}
		fclose($fp);
	}
	
	$ret = "";
	$utf8 = "";
	while ($gbstr != '') {
		if (ord(substr($gbstr, 0, 1)) > 0x80) {
			$thisW = substr($gbstr, 0, 2);
			$gbstr = substr($gbstr, 2, strlen($gbstr));
			$utf8 = "";
			@$utf8 = u2utf8(hexdec($GBK2UTF8_CODETABLE[hexdec(bin2hex($thisW)) - 0x8080]));
			if($utf8 != "") {
				for ($i = 0;$i < strlen($utf8);$i += 3) {
				    $ret .= chr(substr($utf8, $i, 3));
				}
			}
		} else {
			$ret .= substr($gbstr, 0, 1);
			$gbstr = substr($gbstr, 1, strlen($gbstr));
		}
	}
	
	return $ret;
}

//Unicode转utf8
function u2utf8($c) {
	for ($i = 0;$i < count($c);$i++) {
		$str = "";
	}
	
	if ($c < 0x80) {
		$str .= $c;
	} elseif ($c < 0x800) {
		$str .= (0xC0 | $c >> 6);
		$str .= (0x80 | $c & 0x3F);
	} elseif ($c < 0x10000) {
		$str .= (0xE0 | $c >> 12);
		$str .= (0x80 | $c >> 6 & 0x3F);
		$str .= (0x80 | $c & 0x3F);
	} elseif ($c < 0x200000) {
		$str .= (0xF0 | $c >> 18);
		$str .= (0x80 | $c >> 12 & 0x3F);
		$str .= (0x80 | $c >> 6 & 0x3F);
		$str .= (0x80 | $c & 0x3F);
	}
	
	return $str;
}


//utf8转Unicode
function utf82u($c) {
	switch(strlen($c)) {
		case 1:
			return ord($c);
		case 2:
			$n = (ord($c[0]) & 0x3f) << 6;
			$n += ord($c[1]) & 0x3f;
			return $n;
		case 3:
			$n = (ord($c[0]) & 0x1f) << 12;
			$n += (ord($c[1]) & 0x3f) << 6;
			$n += ord($c[2]) & 0x3f;
			return $n;
		case 4:
			$n = (ord($c[0]) & 0x0f) << 18;
			$n += (ord($c[1]) & 0x3f) << 12;
			$n += (ord($c[2]) & 0x3f) << 6;
			$n += ord($c[3]) & 0x3f;
			return $n;
	}
}

if(!function_exists('parse_ini_string')){   
    function parse_ini_string($string) {
        $array = array();

        $lines = explode("\n", $string);
       
        foreach($lines as $line) {
            $statement = preg_match(
"/^(?!;)(?P<key>[\w+\.\-]+?)\s*=\s*(?P<value>.+?)\s*$/", $line, $match);

            if($statement) {
                $key    = $match['key'];
                $value  = $match['value'];
               
                # Remove quote
                if(preg_match("/^\".*\"$/", $value) || preg_match("/^'.*'$/", $value)) {
                    $value = mb_substr($value, 1, mb_strlen($value) - 2);
                }
               
                $array[$key] = $value;
            }
        }
        return $array;
    }
}

/**
 * 获取多行数据
 *
 * @param string $sql
 * @param bool $allowCache
 */
function getRows($sql, $allowCache = false) {
	return UE_DB::factory()->getAll($sql, $allowCache);
}

/**
 * 获取一行数据
 *
 * @param string $sql
 * @param bool $allowCache
 */
function getRow($sql, $allowCache = false) {
	return UE_DB::factory()->getOne($sql, $allowCache);
}

/**
 * 检查功能是否可用
 *
 * @param string $app
 * @param string $ctl
 * @param string $act
 */
function actionIsUsable($app, $ctl, $act) {
	$acls = UE::getEtc('acls');
	$apps = UE::getEtc('apps');
	return !empty($acls[$app][$ctl][$act][$_SESSION['group_id']]) && !empty($apps[$app]['activated']);
}

function mkdirs($dir) {
	mkdir($dir, 0777, true);
}

function getHotTags($num = 10) {
	$sql = "";
}

/**
 * 取得随机整数
 *
 * @param int $len
 * @return int
 */
function randNum($len = 4) {
	$rand = mt_rand(1, 9);
	
	for($i = 0; $i < $len - 1; $i++) {
		$rand .= mt_rand(0, 9);
	}
	
	return $rand;
}
/**
 * 生成图片缩略图
 *
 * @param int $uploadId
 * @param int $width
 * @param int $height
 * @param string $noPic
 * @return string
 */
function thumb($uploadId, $width = 100, $height = 100, $noPic = 'images/nopic.png') {
	$img = UE_DB::factory()->getFirstField("SELECT upload_path FROM ue_upload WHERE upload_id='{$uploadId}' LIMIT 1", 1);
	
	$imgMd5    = md5($img);
	$thumb     = "temp/{$width}x{$height}/{$imgMd5[0]}{$imgMd5[1]}/{$imgMd5}.jpg";
	$thumbUrl  = UE::context().$thumb;
	$thumbFile = SITE_DIR.'/'.$thumb;
	
	if (is_file($thumbFile)) {
		return $thumbUrl;
	}
	
	if (!is_file($img)) {
		return $noPic;
	}
	
	// 生成缩略图
	$suffix = trim(substr($img, strrpos($img, '.') + 1));
	
	if (in_array(strtolower($suffix), array('jpg', 'gif', 'png'))) {
		$image = new UE_Image($img);

		if($image->thumb($width, $height, $thumbFile)) {
			return $thumbUrl;
		}
		
		return $img;
	}
	
	return $noPic;
}
/**
 * 检查是否重新提交
 *
 * @param string $key
 * @param mixed $data
 * @return bool  重新提交返回true，不重新提交返回 false
 */
function isRepost($key, $data) {	
	if (!empty($_SESSION['check_no_repost'][$key]) && $_SESSION['check_no_repost'][$key] == md5(serialize($data))) {
		return true;
	}
	
	$_SESSION['check_no_repost'][$key] = md5(serialize($data));
	return false;
}

/**
 * 发送动态javascript的头信息
 *
 */
function jsHeader() {	
	@header("Expires: -1");
	@header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", false);
	@header("Pragma: no-cache");
	@header("Content-type: application/x-javascript; charset=utf-8");
}